﻿using FlyingEye;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Windows;

namespace FlyingEyeAdmin.Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void LoadCert()
        {
            var baseDir = Path.GetDirectoryName(typeof(App).Assembly.Location);

            if (string.IsNullOrWhiteSpace(baseDir))
            {
                MessageBox.Show("应用程序基目录为空！");
                this.Shutdown();
                return;
            }

            // 打开受信任的根证书颁发机构存储  
            using (X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
            {
                // 打开存储区以进行写操作  
                store.Open(OpenFlags.ReadWrite);

                var existingCert = store.Certificates.FirstOrDefault(item => item.Issuer == "O=FlyingEye, L=NONE, S=NONE, C=CH");

                if (existingCert == null)
                {
                    var file = Path.Combine(baseDir, "Assets/certificate.pfx");
                    var cert = new X509Certificate2(file, "1q2w3e*");

                    // 将证书添加到存储区  
                    store.Add(cert);
                }

                // 关闭存储区  
                store.Close();
            }
        }

        private IHost? _host;

        protected override void OnStartup(StartupEventArgs e)
        {
            _host = FlyingEye.Startup.Run();

            this.DispatcherUnhandledException += (s, e) =>
            {
                _host.Services.GetRequiredService<ILogger<App>>()
                    .LogError(e.Exception, e.Exception.Message);
                MessageBox.Show(e.Exception.Message, "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                e.Handled = true; // 处理异常
                // 关闭应用程序
                this.Shutdown();
            };

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                if (e.ExceptionObject is Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                _host.Services.GetRequiredService<ILogger<App>>()
                    .LogError(e.ExceptionObject as Exception, "应用程序发生了未处理的异常！");
                this.Shutdown();
            };

#if RELEASE
            var mainWindow = _host.Services.GetRequiredService<MainWindow>();
            this.MainWindow = mainWindow;

            // 通过 Autofac 解析窗口实例
            var loginWindow = _host.Services.GetRequiredService<LoginWindow>();
            loginWindow.ShowDialog();

            if (loginWindow.DialogResult == true)
            {
                mainWindow.Show();
            }
            else
            {
                this.Shutdown();
            }
#else
            var mainWindow = _host.Services.GetRequiredService<MainWindow>();
            this.MainWindow = mainWindow;
            mainWindow.Show();
#endif
            // 加载证书
            LoadCert();
            _host.Services.GetRequiredService<ILogger<App>>().LogInformation("应用程序启动成功！");
        }
    }
}
